package com.dfs.parent.sentinel.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;

import com.alibaba.fastjson2.JSONObject;
import com.dfs.parent.common.core.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义熔断异常类
 * 没有定义sentinelResource 直接用簇点链路 捕获不了异常
 *直接返回页面 Blocked by Sentinel (flow limiting)
 *
 */
@Slf4j  // log日志
public class SentinelMVCBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.info("UrlBlockHandler.....................................");
        // 自定义封装的类，可以定义
        Result restObject = null;

        if (e instanceof FlowException) {
            // 限流
            restObject = Result.fail(5001,"接口限流221qyqq");
        } else if (e instanceof DegradeException) {
            // 降级
            restObject = Result.fail(5002,"服务降级221");
        } else if (e instanceof ParamFlowException) {
            // 热点参数
            restObject = Result.fail(5003,"热点参数限流221");
        } else if (e instanceof SystemBlockException) {
            // 系统保护
            restObject = Result.fail(5004,"触发系统保护规则221");
        } else if (e instanceof AuthorityException) {
            // 授权规则
            restObject = Result.fail(5005,"授权规则不通过221");
        }

        //返回json数据
//        response.setStatus(200);
//        response.setCharacterEncoding("utf-8");
//        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//        //springmvc 的一个json转换类 （jackson）
        /**
         * TODO 改成JSONObject json = FastJsonUtil.objToFullJSONObject(restObject)
         *       response.getWriter().print(json);
         */

//        new ObjectMapper().writeValue(response.getWriter(), restObject);

//        JSONObject json = FastJsonUtil.objToFullJSONObject(restObject)
//        response.getWriter().print(json);
//        response.getWriter().print(JSONObject.toJSONString(restObject));


        // http状态码
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSONObject.toJSONString(restObject));
       // response.getWriter().write(JSONUtil.toJsonStr(Result.fail(msg)));
       // response.setContentType(MediaType.APPLICATION_JSON_VALUE);


    }
}
